<?php

namespace app\admin\model;

use addons\thirdwork\library\Application;
use fast\Tree;
use think\Model;

class UserDepartment extends Model
{

    // 表名
    protected $name = 'user_department';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'status_text'
    ];

    protected static function init()
    {
        // self::afterInsert(function ($row) {
        //     $pk = $row->getPk();
        //     $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        // });
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public static function getTreeList($selected = [])
    {
        $ruleList = collection(self::where('status', 'normal')->order('weigh desc,id desc')->select())->toArray();
        $nodeList = [];
        Tree::instance()->init($ruleList);
        $ruleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
        $hasChildrens = [];
        foreach ($ruleList as $k => $v)
        {
            if ($v['haschild'])
                $hasChildrens[] = $v['id'];
        }
        foreach ($ruleList as $k => $v) {
            $state = array('selected' => in_array($v['id'], $selected) && !in_array($v['id'], $hasChildrens));
            $nodeList[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['title']), 'type' => 'menu', 'state' => $state);
        }
        return $nodeList;
    }

	public static function syncData($output = NULL)
	{
		$config = get_addon_config('thirdwork');
		$app    = new Application($config);
		$list   = $app->wechatwork->getDepartmentList();
		if (empty($list['code'])) {
			if ($output) {
				$output->error('接口未返回正常数据');
			}
			return FALSE;
		}
		if ($list['data']) {
			UserDepartment::update(['status' => 'hidden'], ['status' => 'normal', 'id' => ['>', 1]]); //先更新全部部门为隐藏
			foreach ($list['data'] as $item) {
				$data  = [
					'id'     => $item['id'],
					'pid'    => $item['parentid'],
					'name'   => $item['name'],
					'weigh'  => $item['order'],
					'status' => 'normal'
				];
				$check = UserDepartment::get($item['id']);
				if ($check) {
					if ($output) {
						$output->info('[' . date('Y-m-d H:i:s') . '] 更新部门：' . $item['name']);
					}
					UserDepartment::update($data, ['id' => $item['id']]);
				} else {
					if ($output) {
						$output->info('[' . date('Y-m-d H:i:s') . '] 创建部门：' . $item['name']);
					}
					UserDepartment::create($data);
				}
			}
		}
		return TRUE;
	}
}
